<template class="p15">
  <el-card class="accountaddbox">
    <div slot="header">添加账号</div>
    <el-form
      status-icon
      :rules="rules"
      size="small"
      label-width="80px"
      class="form"
      :model="formData"
      ref="formRef"
    >
      <el-form-item label="账号" prop="account">
        <el-input v-model="formData.account"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="formData.password"></el-input>
      </el-form-item>
      <el-form-item label="用户组" prop="userGroup">
        <el-select placeholder="请选择用户组" v-model="formData.userGroup">
          <el-option value="超级管理员" label="超级管理员"></el-option>
          <el-option value="普通管理员" label="普通管理员"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="submit" type="primary" style="color: black"
          >添加</el-button
        >
        <el-button @click="reset" type="default">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import {addUserReq} from '@/api/user'
// 验证用户
const checkAccount = (rule, value, callback) => {
  if (!value) {
    callback(new Error("请输入用户名"));
  } else if (!/^[\u4E00-\u9FA5a-zA-Z0-9]{4,16}$/.test(value)) {
    callback(new Error("请输入正确的用户名"));
  } else {
    callback();
  }
};
// 验证密码
const checkPassword = (rule, value, callback) => {
  if (!value) {
    callback(new Error("请输入密码"));
  } else if (!/^[\u4E00-\u9FA5a-zA-Z0-9]{4,16}$/.test(value)) {
    callback(new Error("请输入正确的密码"));
  } else {
    callback();
  }
};
export default {
  data() {
    return {
      formData: {
        account: "",
        password: "",
        userGroup: "",
      },
      rules: {
        account: [{ validator: checkAccount, trigger: "blur" }],
        password: [{ validator: checkPassword, trigger: "blur" }],
        userGroup: [
          { required: true, message: "请选择用户组", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    //提交验证
    submit() {
      this.$refs.formRef.validate( async valid => {
        console.log("valid :>> ", valid);
        if (valid) {
          // 发送请求
          let res = await addUserReq(this.formData)
          // 解构数据
          let {code, msg} = res.data
          // 判断
          if (code === 0) {
            // 跳转
            this.$router.push('/account')
          }
        }
      });
    },
    // 重置表单
    reset() {
      this.$refs.formRef.resetFields();
    },
  },
};
</script>

<style lang="scss" scoped>
* {
  height: 100%;
}
</style>